package com.sky.service.impl;

import com.sky.constant.StatusConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.mapper.inducts.InductsDishMapper;
import com.sky.mapper.inducts.InductsSetmealMapper;
import com.sky.service.WorkspaceService;
import com.sky.vo.BusinessDataVO;
import com.sky.vo.DishOverViewVO;
import com.sky.vo.OrderOverViewVO;
import com.sky.vo.SetmealOverViewVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WorkspaceServiceImpl implements WorkspaceService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private InductsDishMapper inductsDishMapper;
    @Autowired
    private InductsSetmealMapper inductsSetmealMapper;

    /**
     * 根据时间段统计营业数据
     * @param begin
     * @param end
     * @return
     */
    public BusinessDataVO getBusinessData(LocalDateTime begin, LocalDateTime end) {
        /**
         * 营业额：当日已完成订单的总金额
         * 有效订单：当日已完成订单的数量
         * 订单完成率：有效订单数 / 总订单数
         * 平均客单价：营业额 / 有效订单数
         * 新增用户：当日新增用户的数量
         */

        Map map = new HashMap();
        map.put("begin",begin);
        map.put("end",end);

        //查询总订单数
        Integer totalOrderCount = orderMapper.countByMap(map);

        map.put("status", Orders.COMPLETED);
        //营业额
        Double turnover = orderMapper.sumByMap(map);
        turnover = turnover == null? 0.0 : turnover;

        //有效订单数
        Integer validOrderCount = orderMapper.countByMap(map);

        Double unitPrice = 0.0;

        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0 && validOrderCount != 0){
            //订单完成率
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
            //平均客单价
            unitPrice = turnover / validOrderCount;
        }

        //新增用户数
        Integer newUsers = userMapper.countByMap(map);

        return BusinessDataVO.builder()
                .turnover(turnover)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .unitPrice(unitPrice)
                .newUsers(newUsers)
                .build();
    }


    /**
     * 查询订单管理数据
     *
     * @return
     */
    public OrderOverViewVO getOrderOverView() {
        Map map = new HashMap();
        map.put("begin", LocalDateTime.now().with(LocalTime.MIN));
        map.put("status", Orders.TO_BE_CONFIRMED);

        //待接单
        Integer waitingOrders = orderMapper.countByMap(map);

        //待派送
        map.put("status", Orders.CONFIRMED);
        Integer deliveredOrders = orderMapper.countByMap(map);

        //已完成
        map.put("status", Orders.COMPLETED);
        Integer completedOrders = orderMapper.countByMap(map);

        //已取消
        map.put("status", Orders.CANCELLED);
        Integer cancelledOrders = orderMapper.countByMap(map);

        //全部订单
        map.put("status", null);
        Integer allOrders = orderMapper.countByMap(map);

        return OrderOverViewVO.builder()
                .waitingOrders(waitingOrders)
                .deliveredOrders(deliveredOrders)
                .completedOrders(completedOrders)
                .cancelledOrders(cancelledOrders)
                .allOrders(allOrders)
                .build();
    }

    /**
     * 查询菜品总览
     *
     * @return
     */
    public DishOverViewVO getDishOverView() {
        Map map = new HashMap();
        map.put("status", StatusConstant.ENABLE);
        Integer sold = inductsDishMapper.countByMap(map);

        map.put("status", StatusConstant.DISABLE);
        Integer discontinued = inductsDishMapper.countByMap(map);

        return DishOverViewVO.builder()
                .sold(sold)
                .discontinued(discontinued)
                .build();
    }

    /**
     * 查询套餐总览
     *
     * @return
     */
    public SetmealOverViewVO getSetmealOverView() {
        Map map = new HashMap();
        map.put("status", StatusConstant.ENABLE);
        Integer sold = inductsSetmealMapper.countByMap(map);

        map.put("status", StatusConstant.DISABLE);
        Integer discontinued = inductsSetmealMapper.countByMap(map);

        return SetmealOverViewVO.builder()
                .sold(sold)
                .discontinued(discontinued)
                .build();
    }

    /**
     * 导出前30天数据
     * @return
     */
    @Override
    public XSSFWorkbook export() {
        // 获取模板
        InputStream template = getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        XSSFWorkbook xlsx = null;
        try {
            xlsx = new XSSFWorkbook(template);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if(template != null) {
                try {
                    template.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        XSSFSheet sheet1 = xlsx.getSheet("sheet1");

        // 插入数据
        LocalDate now = LocalDate.now();
        LocalDate before30 = now.minusDays(30);
        LocalDate before1 = now.minusDays(1);

        BusinessDataVO businessData = getBusinessData(LocalDateTime.of(before30, LocalTime.MIN), LocalDateTime.of(before1, LocalTime.MAX));

        sheet1.getRow(1).getCell(1).setCellValue(before30+"~"+before1);

        XSSFRow row4 = sheet1.getRow(3);
        row4.getCell(2).setCellValue(businessData.getTurnover());
        row4.getCell(4).setCellValue(businessData.getOrderCompletionRate());
        row4.getCell(6).setCellValue(businessData.getNewUsers());

        XSSFRow row5 = sheet1.getRow(4);
        row5.getCell(2).setCellValue(businessData.getValidOrderCount());
        row5.getCell(4).setCellValue(businessData.getUnitPrice());

        for (int i = 0; i < 30; i++) {
            LocalDate date = before30.plusDays(i);

            BusinessDataVO everyDateData = getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

            XSSFRow row = sheet1.getRow(7+i);
            row.getCell(1).setCellValue(String.valueOf(date));
            row.getCell(2).setCellValue(everyDateData.getTurnover());
            row.getCell(3).setCellValue(everyDateData.getValidOrderCount());
            row.getCell(4).setCellValue(everyDateData.getOrderCompletionRate());
            row.getCell(5).setCellValue(everyDateData.getUnitPrice());
            row.getCell(6).setCellValue(everyDateData.getNewUsers());
        }

        return xlsx;
    }
}
